package com.config.db;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.Environment;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

@Configuration
@EnableTransactionManagement
// JPA Repository扫描路径
@EnableJpaRepositories(
        basePackages = "com.mapper.repository.mysql",
        entityManagerFactoryRef = "primaryEntityManagerFactory",
        transactionManagerRef = "primaryTransactionManager"
)
public class PrimaryDataSourceConfig {

    // 配置主数据源的实体管理器工厂
    @Primary
    @Bean(name = "primaryEntityManagerFactory")
    public LocalContainerEntityManagerFactoryBean primaryEntityManagerFactory(
            EntityManagerFactoryBuilder builder,
            @Qualifier("mysqlDataSource") DataSource dataSource) {
        return builder
                .dataSource(dataSource)
                .packages("com.bean")  // 主数据源实体类包路径
                .persistenceUnit("primaryPersistenceUnit")
                .properties(jpaProperties("spring.jpa.mysql.properties"))
                .build();
    }

    // 配置主数据源的事务管理器
    @Primary
    @Bean(name = "primaryTransactionManager")
    public PlatformTransactionManager primaryTransactionManager(
            @Qualifier("primaryEntityManagerFactory") EntityManagerFactory entityManagerFactory) {
        return new JpaTransactionManager(entityManagerFactory);
    }

    // 加载JPA配置属性
    private Map<String, Object> jpaProperties(String prefix) {
        Map<String, Object> properties = new HashMap<>();

        properties.put("hibernate.dialect", environment.getProperty(prefix + ".hibernate.dialect"));
        properties.put("hibernate.format_sql", environment.getProperty(prefix + ".hibernate.format_sql"));

        System.out.println("ddl-auto:"+environment.getProperty("spring.jpa.mysql.hibernate.ddl-auto"));
        //自动更新
        properties.put("hibernate.hbm2ddl.auto", environment.getProperty("spring.jpa.mysql.hibernate.ddl-auto"));

        return properties;
    }

    @Autowired
    private Environment environment;
}
